<template>
  <!-- 正常维护工单，试验工单, 计划检修 -->
  <div class="normalMaintenance flowCloumn h100">
    <div class="constentmain h100">
      <div class="tableContent">
        <listTableNew v-bind="tableSetting" ref="klTable"></listTableNew>
      </div>
      <div class="annotations list-table-main" v-if="showType != 'dialogQuery'">
        注：
        <span class="circle normal-bg"></span>
        按期的工单
        <span class="circle remind-bg"></span>
        即将到期的工单
        <span class="circle warning-bg"></span>
        已超期的工单
        <span class="circle gray-bg"></span>
        已废弃工单
      </div>
    </div>
  </div>
</template>
<script>
/* 正常维护工单 */
import {
  getListApi, //列表
} from "@/api/orderManagement/normalMaintenance";
/* 试验工单 */
import {
  getListApi as getExperimentListApi, //列表
} from "@/api/orderManagement/experimentOrder";
/* 计划检修 */
import {
  getListApi as getRepairListApi, //列表
} from "@/api/orderManagement/planRepair";
export default {
  components: {},
  props: {
    showType: {
      type: String,
      default: "",
    },
    ordeType: {
      type: String,
      default: "",
    },
    //设备台账当前设备
    currentNode: {
      type: Object,
      default: () => {
        return {};
      },
    },
    planId: {
      type: String,
      default: "",
    },
    isEquipment: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      userInfo: this.$store.getters.userInfo,
      pageType: "list",
      formData: {},
      currentDevice: {},
      tableSetting: {
        // selectionShow: true,
        showCustomBtn: true, //是否显示自定义列按钮
        showFilterBtn: true, //是否显示过滤器按钮
        pageConfig: {
          pageCode: this.$route.name, //页面标识，用来存储过滤器以及自定义列的时候用
          userId: this.$store.getters.userInfo.id,
        },
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15,
          },
          searchArr: [
            {
              type: "input",
              label: "标题",
              model: "title",
            },
            {
              type: "dept",
              label: "设备管理单位",
              model: "deptManageName",
              idsStr: "deptManage",
              clearable: true,
            },
            {
              type: "device",
              label: "设备",
              model: "equipmentName",
              idsStr: "equipmentId",
            },
            {
              type: "dept",
              label: "作业单位",
              model: "deptWorkName",
              idsStr: "deptWork",
              clearable: true,
            },
            {
              label: "状态",
              model: "statusList",
              type: "select",
              multiple: true,
              option: this.$store.getters["dirtData"]("order_maintain_status"),
            },
            {
              type: "input",
              label: "工单编号",
              model: "code",
            },
            {
              label: "创建时间",
              model: "createTime",
              type: "datetimerange",
            },
            {
              type: "userOnly",
              label: "创建人",
              model: "createByName",
              idsStr: "createBy",
              placeholder: "请输入",
            },
            {
              label: "计划时间",
              model: "planTime",
              type: "datetimerange",
            },
            {
              label: "工单来源",
              model: "sourceId",
              type: "select",
              option: this.$store.getters["dirtData"]("order_source"),
            },
          ],
        },
        actionList: [
          {
            name: "新建",
            icon: "el-icon-plus",
            method: (row) => {
              this.toAdd();
            },
            disabled: !this.$store.getters["isBtnAuth"]("add"),
            content: "未授权此功能！",
          },
        ],
        column: [
          {
            label: "状态",
            prop: "status",
            scopeType: "formate",
            method: (row) => {
              let dom = "";
              let statusName =
                this.$store.getters["fineDirtDataName"](
                  "order_all_status",
                  row.status
                ) || row.status;
              let colorStatus = row.trafficLight;
              if (row.status == "DEPRECATED") {
                dom =
                  '<span class="gray" title="废弃工单">' +
                  statusName +
                  "</span>";
              } else {
                if (colorStatus == "Normal") {
                  //正常
                  dom =
                    '<span class="normal" title="按期的工单">' +
                    statusName +
                    "</span>";
                } else if (colorStatus == "Warn") {
                  //即将到期
                  dom =
                    '<span class="remind" title="即将到期的工单">' +
                    statusName +
                    "</span>";
                } else if (colorStatus == "OverTime") {
                  //超期
                  dom =
                    '<span class="warning" title="已超期工单">' +
                    statusName +
                    "</span>";
                }
              }
              return dom;
            },
            sortable: "custom",
            width: "100px",
          },
          {
            label: "编号",
            prop: "code",
            sortable: "custom",
            showTooltip: true,
            width: "180px",
          },
          {
            label: "标题",
            prop: "title",
            sortable: "custom",
            showTooltip: true,
            width: "320px",
          },
          {
            label: "设备管理单位",
            id: "deptManage",
            prop: "deptManageName",
            sortable: "custom",
            showTooltip: true,
            minWidth: "180px",
          },
          {
            label: "设备",
            prop: "orderEquipPoList",
            sortable: "custom",
            scopeType: "formate",
            formatter: (row) => {
              let name = [];
              if (row.needStatus == 1) {
                switch (this.menuType) {
                  case "repair":
                    name = row.repairEquipmentPos.map((item) => {
                      return item.equipmentName;
                    });
                    break;
                  case "experiment":
                    name = row.experimentEquipmentPos.map((item) => {
                      return item.equipmentName;
                    });
                    break;
                  default:
                    name = row.maintainEquipmentPos.map((item) => {
                      return item.equipmentName;
                    });
                    break;
                }
              } else {
                name = row.orderEquipPoList
                  ? row.orderEquipPoList.map((item) => {
                      return item.equipmentName;
                    })
                  : [];
              }
              return name.toString();
            },
            showTooltip: true,
            minWidth: "210px",
          },
          {
            label: "作业单位",
            prop: "workDeptPoList",
            //sortable: "custom",
            scopeType: "formate",
            formatter: (row) => {
              let worklist = row.workDeptPoList || [];
              let name = [];
              if (worklist.length > 0) {
                worklist.map((i) => {
                  name.push(i.workDeptName);
                });
              }
              return name.toString();
            },
            showTooltip: true,
            width: "240px",
          },
          {
            label: "关联大修工单编号",
            prop: "overhaulCode",
            sortable: "custom",
            minWidth: "220px",
          },
          {
            label: "计划开始时间",
            prop: "startTime",
            sortable: "custom",
            minWidth: "140px",
          },
          {
            label: "计划结束时间",
            prop: "endTime",
            sortable: "custom",
            minWidth: "140px",
          },
          {
            label: "工单来源",
            prop: "sourceId",
            formatter: (row) => {
              let value = row.sourceId;
              return (
                this.$store.getters["fineDirtDataName"](
                  "order_source",
                  value
                ) || value
              );
            },
            sortable: "custom",
            minWidth: "120px",
          },
          {
            label: "创建人",
            prop: "createByName",
            sortable: "custom",
            minWidth: "90px",
          },
          {
            label: "创建时间",
            prop: "createTime",
            sortable: "custom",
            minWidth: "140px",
          },
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (val) => {
            if (this.showType != "dialogQuery") {
              this.gotoDetails(val);
            }
          },
        },
      },
    };
  },
  watch: {
    currentNode: {
      handler: function (newVal, oldVal) {
        this.currentDevice = Object.assign({}, newVal);
        let queryData = Object.assign(this.tableSetting.searchObj.queryData, {
          equipmentId: newVal.id,
          collectionSearch: true,
          floor: newVal.floor,
        });
        this.tableSetting.searchObj.queryData = {};
        this.tableSetting.searchObj.queryData = queryData;
        setTimeout(() => {
          if (oldVal) {
            //不是第一次
            this.updateData();
          }
        }, 0);
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    menuType() {
      let obj = {
        normalMaintenance: "maintain",
        experimentOrder: "experiment",
        planRepair: "repair",
      };
      let menuType = obj[this.$route.name];
      return menuType || this.ordeType;
    },
  },
  created() {
    if (this.planId != "") {
      // this.tableSetting.showCustomBtn = false;
      // this.tableSetting.showFilterBtn = false;
      let queryData = Object.assign(this.tableSetting.searchObj.queryData, {
        planId: this.planId,
      });
      this.tableSetting.searchObj.queryData = queryData;
    }
    if (this.isEquipment) {
      this.tableSetting.searchObj.searchArr.unshift({
        label: "向上归集",
        model: "collectionSearch",
        unclearable: true,
        type: "select",
        option: [
          { label: "是", value: true },
          { label: "否", value: false },
        ],
      });
      this.tableSetting.searchObj.searchArr.splice(3, 1);
      this.tableSetting.column.splice(4, 1);
    }
    /* 添加监听事件 */
    window.addEventListener("storage", this.updateData);
  },
  beforeDestroy() {
    /* 删除监听事件 */
    window.removeEventListener("storage", this.updateData);
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      if (this.showType == "dialogQuery") {
        this.tableSetting.radioShow = true;
        this.tableSetting.selectionShow = false;
        this.tableSetting.showCustomBtn = false;
        this.tableSetting.showFilterBtn = false;
        this.tableSetting.actionList = [];
        this.tableSetting.searchObj.searchArr = [
          {
            type: "input",
            label: "编号",
            model: "code",
          },
          {
            type: "input",
            label: "标题",
            model: "title",
          },
        ];
        this.tableSetting.column = [
          {
            label: "编号",
            prop: "code",
            sortable: "custom",
          },
          {
            label: "标题",
            prop: "title",
            sortable: "custom",
          },
          {
            label: "设备管理单位",
            id: "deptManage",
            prop: "deptManageName",
            sortable: "custom",
          },
          {
            label: "作业单位",
            prop: "locationName",
            sortable: "custom",
          },
        ];
        /* 初始化查询条件 */
        this.tableSetting.searchObj.queryData = {
          page: 1,
          pageSize: 15,
          statusList: ["WAIT_EXECUTE", "IN_EXECUTE", "ARCHIVED"],
        };
      } else if (this.showType == "query") {
        this.tableSetting.selectionShow = false;
        this.tableSetting.showCustomBtn = false;
        this.tableSetting.showFilterBtn = false;
        this.tableSetting.actionList = [];
      } else if (this.showType == "plan") {
        this.tableSetting.selectionShow = false;
        this.tableSetting.showCustomBtn = false;
        this.tableSetting.showFilterBtn = false;
        this.tableSetting.actionList = [];
        this.tableSetting.searchObj.searchArr = [
          {
            type: "input",
            label: "编号",
            model: "code",
          },
          {
            type: "input",
            label: "标题",
            model: "title",
          },
          {
            label: "状态",
            model: "statusList",
            type: "select",
            multiple: true,
            option: this.$store.getters["dirtData"]("order_maintain_status"),
          },
        ];
        this.tableSetting.column = [
          {
            label: "状态",
            prop: "status",
            scopeType: "formate",
            method: (row) => {
              let dom = "";
              let statusName =
                this.$store.getters["fineDirtDataName"](
                  "order_all_status",
                  row.status
                ) || row.status;
              let colorStatus = row.trafficLight;
              if (row.status == "DEPRECATED") {
                dom =
                  '<span class="gray" title="废弃工单">' +
                  statusName +
                  "</span>";
              } else {
                if (colorStatus == "Normal") {
                  //正常
                  dom =
                    '<span class="normal" title="按期的工单">' +
                    statusName +
                    "</span>";
                } else if (colorStatus == "Warn") {
                  //即将到期
                  dom =
                    '<span class="remind" title="即将到期的工单">' +
                    statusName +
                    "</span>";
                } else if (colorStatus == "OverTime") {
                  //超期
                  dom =
                    '<span class="warning" title="已超期工单">' +
                    statusName +
                    "</span>";
                }
              }
              return dom;
            },
            sortable: "custom",
          },
          {
            label: "编号",
            prop: "code",
            sortable: "custom",
          },
          {
            label: "标题",
            prop: "title",
            sortable: "custom",
            showTooltip: true,
          },
          {
            label: "设备管理单位",
            id: "deptManage",
            prop: "deptManageName",
            sortable: "custom",
          },
          {
            label: "设备",
            prop: "orderEquipPoList",
            sortable: "custom",
            scopeType: "formate",
            showTooltip: true,
            formatter: (row) => {
              let name = [];
              if (row.needStatus == 1) {
                switch (this.menuType) {
                  case "repair":
                    name = row.repairEquipmentPos.map((item) => {
                      return item.equipmentName;
                    });
                    break;
                  case "experiment":
                    name = row.experimentEquipmentPos.map((item) => {
                      return item.equipmentName;
                    });
                    break;
                  default:
                    name = row.maintainEquipmentPos.map((item) => {
                      return item.equipmentName;
                    });
                    break;
                }
              } else {
                name = row.orderEquipPoList
                  ? row.orderEquipPoList.map((item) => {
                      return item.equipmentName;
                    })
                  : [];
              }
              return name.toString();
            },
            width: "240px",
          },
          {
            label: "作业单位",
            prop: "workDeptPoList",
            //sortable: "custom",
            scopeType: "formate",
            formatter: (row) => {
              let worklist = row.workDeptPoList || [];
              let name = [];
              if (worklist.length > 0) {
                worklist.map((i) => {
                  name.push(i.workDeptName);
                });
              }
              return name.toString();
            },
            showTooltip: true,
            width: "240px",
          },
          {
            label: "计划开始时间",
            prop: "startTime",
            sortable: "custom",
          },
          {
            label: "计划结束时间",
            prop: "endTime",
            sortable: "custom",
          },
        ];
      } else {
        this.$refs.klTable.getTableConfig(); //需要显示过滤器以及自定义列时要提前调用,不需要过滤器时不调用
      }
      /* 当为试验工单时，展示关联的大修工单的编号 */
      let column = this.tableSetting.column;
      for (let i = 0; i < column.length; i++) {
        if (column[i].prop == "overhaulCode") {
          if (this.menuType == "experiment") {
            column[i].hide = false;
          } else {
            column[i].hide = true;
          }
        }
      }
      if (this.menuType == "experiment") {
        let arr = JSON.parse(
          JSON.stringify(this.tableSetting.searchObj.searchArr)
        );
        for (let i in arr) {
          if (arr[i].model == "statusList") {
            arr[i].option = this.$store.getters["dirtData"](
              "order_experiment_type"
            );
            break;
          }
        }
        this.tableSetting.searchObj.searchArr = arr;
      }
      if (["query", "dialogQuery", "plan"].includes(this.showType)) {
        setTimeout(() => {
          this.updateData();
        }, 500);
      }
    },
    updateData() {
      this.$refs.klTable.searchData();
    },
    getTableData(params, sortStr) {
      let form = { ...params };
      if (sortStr) {
        form.orders = sortStr;
      }
      if (form.planTime) {
        form.startTime = form.planTime[0];
        form.endTime = form.planTime[1];
        delete form.planTime;
      }
      if (form.createTime) {
        form.createStartTime = form.createTime[0];
        form.createEndTime = form.createTime[1];
        delete form.createTime;
      }
      if (!this.isEquipment) {
        form.collectionSearch = false;
        delete form.floor;
      }
      var actionApi = null;
      if (this.menuType == "maintain" || this.ordeType == "maintain") {
        /* 正常维护单 */
        actionApi = getListApi;
      } else if (
        this.menuType == "experiment" ||
        this.ordeType == "experiment"
      ) {
        /* 试验工单 */
        actionApi = getExperimentListApi;
      } else if (this.menuType == "repair" || this.ordeType == "repair") {
        /* 计划检修 */
        actionApi = getRepairListApi;
      }
      actionApi(form)
        .then((res) => {
          let data = res.data.list || [];
          let total = res.data.total || 0;
          this.$set(this.tableSetting, "tableData", data);
          this.$set(this.tableSetting, "totalNumber", total);
        })
        .catch((e) => {
          this.$set(this.tableSetting, "tableData", []);
          this.$set(this.tableSetting, "totalNumber", 0);
        });
    },
    //打开详情页
    gotoDetails(data) {
      if (data) {
        this.pageType = "edit";
      }
      let form = {
        pageType: this.pageType,
      };
      if (this.pageType != "add") {
        form.id = data.id;
        form.status = data.status;
      }
      let pathUrl = "";
      if (this.menuType == "maintain" || this.ordeType == "maintain") {
        //日常维护工单
        pathUrl = "/orderManagement/normalMaintenance/details";
      } else if (
        this.menuType == "experiment" ||
        this.ordeType == "experiment"
      ) {
        //试验工单
        pathUrl = "/orderManagement/experimentOrder/details";
      } else if (this.menuType == "repair" || this.ordeType == "repair") {
        /* 计划检修 */
        pathUrl = "/orderManagement/planRepair/details";
      }
      let { href } = this.$router.resolve({
        path: pathUrl,
        query: form,
      });
      window.open(href, "_blank");
    },
    //新建
    toAdd() {
      this.pageType = "add";
      this.gotoDetails();
    },
    //删除
    deleteRow() {
      let checkRow = this.$refs.klTable.getSelectData() || [];
      if (checkRow.length == 0) {
        this.$message.warning("请先选择要删除的数据！");
      } else {
        let deleteList = [];
        let isDelete = true;
        for (let i = 0; i < checkRow.length; i++) {
          let { id, status, sourceId } = checkRow[i];
          if (["DRAFT"].includes(status) && sourceId == "enter_order") {
            deleteList.push(id);
          } else {
            isDelete = false;
            //只有是草稿状态的数据是可以删除的
            let errorMess = "已提交的数据不能删除！";
            if (sourceId != "enter_order") {
              errorMess = "只能删除手工录入的数据！";
            }
            this.$message.warning(errorMess);
            break;
          }
        }
        let form = {
          ids: deleteList.toString(),
        };
        // if (isDelete) {
        //   this.$confirm(`是否确认删除`, "提示", {
        //     confirmButtonText: "确定",
        //     cancelButtonText: "取消",
        //     type: "warning"
        //   })
        //     .then(() => {
        //       deleteListApi(form).then(res => {
        //         this.$message.success("操作成功");
        //         this.updateData();
        //       });
        //     })
        //     .catch(e => {});
        // }
      }
    },

    //获取选中数据
    getRadioData() {
      let data = this.$refs.klTable.getRadioData();
      return data;
    },
  },
};
</script>
<style lang="less" scoped>
.normalMaintenance {
  min-height: 500px;
  height: 100%;
  text-align: center;
}
.constentmain {
  position: relative;
}
.tableContent {
  min-height: 500px;
  height: 100%;
}
.annotations {
  text-align: left;
  height: 20px;
  line-height: 20px;
  position: absolute;
  bottom: 5px;
}
.circle {
  display: inline-block;
  width: 12px;
  height: 12px;
  border-radius: 10px;
}
</style>
